<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="200"
      placeholder="请输入内容"
      show-word-limit
      clearable
    >
      <van-button
        slot="button"
        size="mini"
        type="info"
        @click="onAddComment"
        :disabled="!message.length"
        >发布</van-button
      >
    </van-field>
    <!-- </van-cell-group> -->
  </div>
</template>

<script>
import { addCommentAPI } from '@/api'
export default {
  name: 'CommentPost',
  components: {},
  props: {
    target: {
      type: [Number, String, Object],
      required: true
    },
    articleId: {
      type: [Number, String, Object]
    }
  },
  data () {
    return {
      message: ''
    }
  },
  methods: {
    async onAddComment () {
      // 非空校验
      if (!this.message.length) {
        return this.$toast.fail('发布内容不能为空')
      }

      try {
        this.$toast.loading({
          message: '发布中...',
          forbidClick: true,
          duration: 1000
        })

        // 请求添加
        const { data: res } = await addCommentAPI({
          // target: this.$route.params.articleId.toString(), // 评论的目标id（评论文章即为文章id，对评论进行回复则为评论id）
          target: this.target.toString(),
          content: this.message, // 评论内容
          art_id: this.articleId ? this.articleId.toString() : this.articleId // 文章id，对评论内容发表回复时，需要传递此参数，表明所属文章id。对文章进行评论，不要传此参数。
        })

        this.$emit('add-comment', res.data.new_obj)
        this.message = ''
        this.$toast('发布成功')
      } catch (error) {
        console.log(error.response)
        if (error.response && error.response.status === 400) {
          return this.$toast.fail('本篇文章不允许评论')
        }
        this.$toast.fail('发布失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 20px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
